/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.util;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import com.jianggujin.dbfly.util.JBeanUtils;
import com.jianggujin.dbfly.util.JDBFlyException;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * lambda属性工具
 * 
 * @author jianggujin
 *
 */
public class JLambdaPropertyUtils {
    private static final Map<String, String> CACHE = new ConcurrentHashMap<>();

    /**
     * 解析属性名称
     * 
     * @param <T>
     * @param <R>
     * @param function
     * @return
     */
    public static <T, R> String resolve(JPropertyFunction<T, R> function) {
        return resolve((Serializable) function);
    }

    /**
     * 解析属性名称
     * 
     * @param <T>
     * @param <U>
     * @param serializable
     * @return
     */
    public static <T, U> String resolve(Serializable serializable) {
        Class<?> clazz = serializable.getClass();
        String name = clazz.getName();
        return Optional.ofNullable(CACHE.get(name)).orElseGet(() -> {
            String property = resolveProperty(serializable);
            CACHE.put(name, property);
            return property;
        });
    }

    private static <T> String resolveProperty(Serializable serializable) {
        SerializedLambda lambda = getSerializedLambda(serializable);
        String methodName = lambda.getImplMethodName();
        if (methodName.startsWith("get")) {
            return JStringUtils.firstCharToLowerCase(methodName.substring(3));
        } else if (methodName.startsWith("is")) {
            return JStringUtils.firstCharToLowerCase(methodName.substring(2));
        }
        throw new JDBFlyException("无效的Getter方法：{}", methodName);
    }

    private static SerializedLambda getSerializedLambda(Serializable serializable) {
        if (!serializable.getClass().isSynthetic()) {
            throw new JDBFlyException("该方法仅能传入lambda表达式产生的合成类");
        }
        return (SerializedLambda) JBeanUtils.invokeMethod(serializable, "writeReplace");
    }
}
